package com.woniuxy.microsysserver.configure;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xpath.internal.operations.String;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

/**
 * @Author Chan
 * @Date 2021/1/29 17:17
 */
@Configuration
public class RedisConfigure {

    /**redis连接工厂*/
    @Resource
    private RedisConnectionFactory factory;

    /**
     * 配置Redis的模板操作类
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(){
        //Redis存储数据为二进制，应针对key-value进行序列化设置
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        //获取连接
        redisTemplate.setConnectionFactory(factory);

        //对key的序列化器设置
        StringRedisSerializer keyRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(keyRedisSerializer);
        redisTemplate.setHashKeySerializer(keyRedisSerializer);

        //对value的序列化器设置(Json)
        Jackson2JsonRedisSerializer valueRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //创建对象映射
        ObjectMapper mapper = new ObjectMapper();

        //指定需要序列化的域
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        valueRedisSerializer.setObjectMapper(mapper);
        redisTemplate.setValueSerializer(valueRedisSerializer);
        redisTemplate.setHashValueSerializer(valueRedisSerializer);

        //初始化参数和初始化工作
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

    /**
     * 针对String类型的对象封装
     * @return
     */
    @Bean
    public ValueOperations<String,Object> valueOperations(){
        return redisTemplate().opsForValue();
    }

    /**
     * 针对List类型的对象封装
     * @return
     */
    @Bean
    public ListOperations<String,Object> listOperations(){
        return redisTemplate().opsForList();
    }

    /**
     * 针对Set类型的对象封装
     * @return
     */
    @Bean
    public SetOperations<String,Object> setOperations(){
        return redisTemplate().opsForSet();
    }


    /**
     * 针对zset类型的对象封装
     * @return
     */
    @Bean
    public ZSetOperations<String,Object> zSetOperations(){
        return redisTemplate().opsForZSet();
    }


    /**
     * 针对Hash类型的对象封装
     * @return
     */
    @Bean
    public HashOperations<String,String,Object> hashOperations(){
        return redisTemplate().opsForHash();
    }


}
